{% extends 'base.html' %}

{% block content %}
<div class="text-center mb-12">
    <h1 class="text-4xl font-bold text-gray-800 mb-4">学生成绩分析与预测系统</h1>
    <p class="text-xl text-gray-600 max-w-3xl mx-auto">
        生成模拟学生成绩数据，进行数据分析并预测期末成绩。探索影响成绩的关键因素，获取个性化学习建议。
    </p>
</div>

<div class="bg-white rounded-xl shadow-lg p-8 max-w-4xl mx-auto mb-12">
    <h2 class="text-2xl font-semibold mb-6 text-gray-800 flex items-center">
        <i class="fa fa-random text-primary mr-3"></i>生成学生成绩数据
    </h2>

    <form id="dataGenerationForm" class="space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label for="num_students" class="block text-sm font-medium text-gray-700 mb-1">学生人数</label>
                <input type="number" id="num_students" name="num_students" min="10" value="1000"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom">
                <p class="mt-1 text-xs text-gray-500">请输入大于1000的数字</p>
            </div>
        </div>

        <div class="border-t border-gray-200 pt-6">
            <h3 class="text-lg font-medium text-gray-800 mb-4">成绩权重设置</h3>
            <p class="text-sm text-gray-500 mb-4">设置各部分成绩在期末总成绩中的占比（总和应为100%）</p>
            <p class="text-sm text-gray-500 mb-4">期末成绩添加±5%的随机波动</p>

            <div class="space-y-4">
                <div>
                    <div class="flex justify-between mb-1">
                        <label for="attendance_weight" class="block text-sm font-medium text-gray-700">出勤成绩</label>
                        <span id="attendance_value" class="text-sm font-medium text-primary">20%</span>
                    </div>
                    <input type="range" id="attendance_weight" name="attendance_weight" min="0" max="100" value="20"
                           class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary">
                </div>

                <div>
                    <div class="flex justify-between mb-1">
                        <label for="homework_weight" class="block text-sm font-medium text-gray-700">作业成绩</label>
                        <span id="homework_value" class="text-sm font-medium text-primary">30%</span>
                    </div>
                    <input type="range" id="homework_weight" name="homework_weight" min="0" max="100" value="30"
                           class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary">
                </div>

                <div>
                    <div class="flex justify-between mb-1">
                        <label for="midterm_weight" class="block text-sm font-medium text-gray-700">期中成绩</label>
                        <span id="midterm_value" class="text-sm font-medium text-primary">50%</span>
                    </div>
                    <input type="range" id="midterm_weight" name="midterm_weight" min="0" max="100" value="50"
                           class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary">
                </div>

                <div class="pt-2">
                    <div class="flex justify-between items-center">
                        <span class="text-sm font-medium text-gray-700">总权重</span>
                        <span id="total_weight" class="text-sm font-bold text-gray-800">100%</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2 mt-1">
                        <div id="weight_progress" class="bg-primary h-2 rounded-full" style="width: 100%"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="pt-4">
            <button type="submit" class="w-full bg-primary hover:bg-blue-600 text-white font-medium py-3 px-4 rounded-lg transition-custom flex items-center justify-center">
                <i class="fa fa-cogs mr-2"></i>生成数据并开始分析
            </button>
        </div>
    </form>
</div>

<div id="dataPreview" class="hidden bg-white rounded-xl shadow-lg p-8 max-w-5xl mx-auto">
    <h2 class="text-2xl font-semibold mb-6 text-gray-800 flex items-center">
        <i class="fa fa-table text-primary mr-3"></i>生成的数据预览
    </h2>

    <div class="overflow-x-auto mb-6">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生ID</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">出勤成绩</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">作业成绩</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">期中成绩</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">期末成绩</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">是否挂科</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分数段</th>
                </tr>
            </thead>
            <tbody id="previewTableBody" class="bg-white divide-y divide-gray-200">
                <!-- 数据将通过JavaScript动态填充 -->
            </tbody>
        </table>
    </div>

    <div class="flex justify-end space-x-4">
        <button id="regenerateBtn" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-custom">
            <i class="fa fa-refresh mr-1"></i>重新生成
        </button>
        <form action="/analyze_data" method="POST">
            <button type="submit" class="px-4 py-2 bg-secondary hover:bg-green-600 text-white rounded-lg transition-custom">
                <i class="fa fa-bar-chart mr-1"></i>进行数据分析
            </button>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 更新权重显示
    const attendanceSlider = document.getElementById('attendance_weight');
    const homeworkSlider = document.getElementById('homework_weight');
    const midtermSlider = document.getElementById('midterm_weight');
    const attendanceValue = document.getElementById('attendance_value');
    const homeworkValue = document.getElementById('homework_value');
    const midtermValue = document.getElementById('midterm_value');
    const totalWeight = document.getElementById('total_weight');
    const weightProgress = document.getElementById('weight_progress');

    function updateWeightDisplay() {
        const attendance = parseInt(attendanceSlider.value);
        const homework = parseInt(homeworkSlider.value);
        const midterm = parseInt(midtermSlider.value);
        const total = attendance + homework + midterm;

        attendanceValue.textContent = `${attendance}%`;
        homeworkValue.textContent = `${homework}%`;
        midtermValue.textContent = `${midterm}%`;
        totalWeight.textContent = `${total}%`;

        // 更新进度条颜色和宽度
        if (total === 100) {
            weightProgress.className = 'bg-secondary h-2 rounded-full';
        } else if (total > 100) {
            weightProgress.className = 'bg-red-500 h-2 rounded-full';
        } else {
            weightProgress.className = 'bg-yellow-500 h-2 rounded-full';
        }
        weightProgress.style.width = `${Math.min(total, 100)}%`;
    }

    attendanceSlider.addEventListener('input', updateWeightDisplay);
    homeworkSlider.addEventListener('input', updateWeightDisplay);
    midtermSlider.addEventListener('input', updateWeightDisplay);

    // 表单提交处理
    const dataGenerationForm = document.getElementById('dataGenerationForm');
    const dataPreview = document.getElementById('dataPreview');
    const previewTableBody = document.getElementById('previewTableBody');
    const regenerateBtn = document.getElementById('regenerateBtn');

    dataGenerationForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        // 验证权重总和
        const attendance = parseInt(attendanceSlider.value);
        const homework = parseInt(homeworkSlider.value);
        const midterm = parseInt(midtermSlider.value);
        const total = attendance + homework + midterm;

        if (total !== 100) {
            alert('权重总和必须为100%，请调整各部分权重。');
            return;
        }

        // 创建表单数据
        const formData = new FormData(dataGenerationForm);

        try {
            // 显示加载状态
            dataGenerationForm.querySelector('button').innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>生成中...';
            dataGenerationForm.querySelector('button').disabled = true;

            // 发送请求
            const response = await fetch('/generate_data', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            // 填充预览表格
            previewTableBody.innerHTML = '';
            result.preview.forEach(student => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-custom';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${student.student_id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.attendance.toFixed(1)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.homework.toFixed(1)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.midterm.toFixed(1)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium ${student.final_grade >= 60 ? 'text-green-600' : 'text-red-600'}">${student.final_grade.toFixed(1)}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${student.failed ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'}">
                            ${student.failed ? '是' : '否'}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.score_range}</td>
                `;
                previewTableBody.appendChild(row);
            });

            // 显示数据预览
            dataPreview.classList.remove('hidden');
            dataPreview.scrollIntoView({ behavior: 'smooth' });

        } catch (error) {
            console.error('Error generating data:', error);
            alert('生成数据时出错，请重试。');
        } finally {
            // 恢复按钮状态
            dataGenerationForm.querySelector('button').innerHTML = '<i class="fa fa-cogs mr-2"></i>生成数据并开始分析';
            dataGenerationForm.querySelector('button').disabled = false;
        }
    });

    // 重新生成按钮
    regenerateBtn.addEventListener('click', () => {
        dataPreview.classList.add('hidden');
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
</script>
{% endblock %}